//worker.c

#include "server.h"

void cleanFunc(void* arg){
    threadPool_t* pThreadPool = (threadPool_t*)arg;
    pthread_mutex_unlock(&pThreadPool->taskQueue.mutex);
}

void* handEvent(void* arg){
    threadPool_t* pThreadPool = (threadPool_t*)arg;
    int netFd;
    while(1){
        printf("I am free! tid = %lu\n", pthread_self());
        pthread_mutex_lock(&pThreadPool->taskQueue.mutex);
        pthread_cleanup_push(cleanFunc, (void*)pThreadPool);
        while(pThreadPool->taskQueue.size == 0 && pThreadPool->exitFlag == 0){
            pthread_cond_wait(&pThreadPool->taskQueue.cond, &pThreadPool->taskQueue.mutex);
        }
        if(pThreadPool->exitFlag == 1){
            printf("I am going to die! child thread.\n");
            pthread_exit(NULL);
        }
        netFd = pThreadPool->taskQueue.pFront->netFd;//拿到队首的文件描述符
        taskDequeue(&pThreadPool->taskQueue);
        pthread_cleanup_pop(1);

        printf("I am working! tid = %lu\n", pthread_self());

        sendFile(netFd, "file1");

        printf("done\n");
        close(netFd);
    }
}

int makeWorker(threadPool_t* pThreadPool){
    for(int i=0;i<pThreadPool->threadNum;i++){
        pthread_create(&pThreadPool->tid[i], NULL, handEvent, (void*)pThreadPool);
    }
}